package org.phalanx.server.ServerCache;

import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;

public class CacheListenerManager {
	private Hashtable<String, ArrayList<CacheListener>> listenerTable;
	public static final String EVENT_ADDED = "ADDED";
	public static final String EVENT_DELETED = "DELETED";
	public static final String EVENT_UPDATED = "UPDATED";

	public CacheListenerManager(){
		listenerTable = new Hashtable<String, ArrayList<CacheListener>>();
	}

	public void addListener(String cacheName, CacheListener cl){
		if (cl != null && cacheName != null && !cacheName.isEmpty()){
			ArrayList<CacheListener> clArray = listenerTable.get(cacheName);

			if (clArray != null){
				if (!clArray.contains(cl)){
					clArray.add(cl);
				}
			} else {
				clArray = new ArrayList<CacheListener>();
				clArray.add(cl);
				listenerTable.put(cacheName, clArray);
			}
		}
	}

	public void removeListener(String cacheName, CacheListener cl){
		if (cl != null && cacheName != null && !cacheName.isEmpty()){
			ArrayList<CacheListener> clArray = listenerTable.get(cacheName);

			if (clArray != null){
				if (clArray.contains(cl)){
					clArray.remove(cl);

					if (clArray.isEmpty()){
						listenerTable.remove(cacheName);
					}
				}
			}
		}
	}

	public void removeAllListeners(String cacheName){
		if (cacheName != null && !cacheName.isEmpty()){
			if (listenerTable.containsKey(cacheName)){
				listenerTable.remove(cacheName);
			}
		}
	}

	public void fireCacheEvent(String action, String cacheName, Cacheable c, boolean dbUpdated){
		if (cacheName != null && !cacheName.isEmpty()){
			ArrayList<CacheListener> clArray = listenerTable.get(cacheName);

			if (clArray != null){
				Iterator<CacheListener> i = clArray.iterator();

				while (i.hasNext()){
					CacheListener cl = i.next();

					if (action.equals(EVENT_ADDED)){
						cl.onCacheAdded(c, cacheName, dbUpdated);
					} else if (action.equals(EVENT_DELETED)){
						cl.onCacheDeleted(c, cacheName, dbUpdated);
					} else if (action.equals(EVENT_UPDATED)){
						cl.onCacheModified(c, cacheName, dbUpdated);
					}
				}
			}
		}
	}
}
